#include "../../server.hpp"

std::unordered_map<uint64_t, PtrConnection> _conns;
uint64_t conn_id = 0;
EventLoop base_loop;         //主线程的监听 loop
std::vector<LoopThread> threads(2);
int next_id = 1;

void ConnectionDestroy(const PtrConnection &conn){
    _conns.erase(conn->Id());
}

void OnMessage(const PtrConnection &conn, Buffer *buf){
    DEBUG_LOG("%s", buf->read_pos());
    buf->move_reader(buf->readable_size());
    std::string str = "hello cli";
    conn->Send(str.c_str(), str.size());
    conn->ShutDown();
}

void OnConnected(const PtrConnection &conn){
    DEBUG_LOG("New Connection: %p", conn.get());
}

void AcceptorCallback(int newfd){
    DEBUG_LOG("accepted: %d", newfd);
    if(newfd < 0) return;

    conn_id++;
    next_id = (next_id+1) % 2;
    PtrConnection conn(new Connection(threads[next_id].Loop(), conn_id, newfd));
    
    conn->SetMessageCallback(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));
    conn->SetSvrClosedCallback(std::bind(ConnectionDestroy, std::placeholders::_1));
    conn->SetConnectedCallback(std::bind(OnConnected, std::placeholders::_1));
    conn->EnableInactiveRelease(10);
    conn->Established();
    _conns.insert(std::make_pair(conn_id, conn));
    DEBUG_LOG("NEW THREAD");
}

int main(){

    Acceptor acceptor(&base_loop, 8500);
    
    acceptor.SetOnAcceptCallback(std::bind(AcceptorCallback, std::placeholders::_1));
    acceptor.Listen(); // enable_read
    while(true){
        base_loop.Start();
        // sleep(1);
    }

    return 0;
}